package com.zhangxiaofanfan.hotcode.second;

import java.util.Stack;

/**
 *
 *
 * @date 2024-06-29 03:21:25
 * @author zhangxiaofanfan
 */
public class HotCode071 {
    public static void main(String[] args) {
        HotCode071 hotCode = new HotCode071();
        String s = "3[a2[c]]";
        System.out.println(hotCode.decodeString(s));
    }

    public String decodeString(String s) {
        if (s == null || s.isEmpty()) {
            return "";
        }
        Stack<String> stack = new Stack<>();
        Stack<Integer> stackInteger = new Stack<>();
        Stack<String> outStack = new Stack<>();
        int count = 0;
        for (char c : s.toCharArray()) {
            if (c == ']') {
                count = 0;
                StringBuffer stringBuffer = new StringBuffer();
                StringBuffer temp = new StringBuffer();
                while (!stack.peek().equals("[")) {
                    outStack.push(stack.pop());
                }
                stack.pop();
                while (!stack.isEmpty() && Character.isDigit(stack.peek().charAt(0))) {
                    stackInteger.push(Integer.parseInt(stack.pop()));
                }
                while (!stackInteger.isEmpty()) {
                    count = count * 10 + stackInteger.pop();
                }
                while (!outStack.isEmpty()) {
                    stringBuffer.append(outStack.pop());
                }
                temp.append(String.valueOf(stringBuffer).repeat(Math.max(0, count)));
                stack.push(temp.toString());
            } else {
                stack.push(c + "");
            }
        }
        while (!stack.isEmpty()) outStack.push(stack.pop());
        StringBuffer result = new StringBuffer();
        while (!outStack.isEmpty()) result.append(outStack.pop());
        return result.toString();
    }

}
